/**
 * @copyright 2017 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */
package com.sinping.qh.api.auth;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.domain.auth.SystemConfig;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.dto.auth.SystemConfigDTO;
import com.sinping.qh.service.auth.ISystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统参数管理
 *
 * @author 陈长石
 * @create 2017/12/19
 */
@Api(value = "Admin系统参数管理", description = "Admin系统参数的增删改查API")
@RestController
@RequestMapping(value = Const.BASE_URI + "/parameter", name = "系统参数管理")
public class SystemConfigEndPoint {

    private final static Logger logger = LoggerFactory.getLogger(SystemConfigEndPoint.class);

    @Autowired
    private ISystemConfigService systemConfigService;

    /**
     * 系统参数列表,分页
     *
     * @param msg
     * @return ResDto
     */
    @ApiParam("msg")
    @ApiOperation(value = "系统参数列表", notes = "起始页，每页条数")
    @RequestMapping(method = RequestMethod.GET, name = "系统参数列表")
    public ResDto listPage(@RequestParam(required = true)
                           @ApiParam(name = "msg", value = "{\"page_size\":10, \"page_no\":1, \"order_column\":null, \"order_by\":null, \"condition\":{\"`key`\":\"log\"}}")
                                   String msg) {
        try {
            logger.info("入参 {}", msg);
            FrontPage<SystemConfig> page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if(page == null){
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            Wrapper<SystemConfig> systemConfigWrapper = new EntityWrapper<>();
            systemConfigWrapper.allEq(page.getCondition());
            String msgResult = null;
            if (page.getPage() == 0) {
                //不分页
                if(StringUtils.isBlank(page.getProp())){
                    systemConfigWrapper.orderBy("create_time", false);
                }
                List<SystemConfig> listResult = systemConfigService.selectList(systemConfigWrapper);
                List<SystemConfigDTO> listDto = BeanMapper.mapList(listResult, SystemConfigDTO.class);
                FrontPage frontPage = new FrontPage<SystemConfigDTO>();
                frontPage.setRecords(listDto);
                msgResult = JsonMapper.defaultMapper().toJson(frontPage);
            } else {
                //分页
                Page<SystemConfig> pageResult = systemConfigService.selectPage(page.toPagePlus(), systemConfigWrapper);
                FrontPage frontPage = new FrontPage(pageResult);
                frontPage.setRecords(BeanMapper.mapList(pageResult.getRecords(), SystemConfigDTO.class));
                msgResult = JsonMapper.defaultMapper().toJson(frontPage);
            }
            return new ResDto(ConstEum.SUCCESS, msgResult);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }

    /**
     * 单个参数查询
     *
     * @param id
     * @return ResDto
     */
    @ApiParam("id")
    @ApiOperation(value = "按ID查询", notes = "按ID查询")
    @RequestMapping(value = "/${id}", method = RequestMethod.GET, name = "按ID查询")
    public ResDto getById(@PathVariable String id) {
        try {
            logger.info("入参 {}", id);
            if (StringUtils.isBlank(id)) {
                logger.error("ID不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            SystemConfig systemConfig = systemConfigService.selectById(id);
            String msgResult = JsonMapper.defaultMapper().toJson(BeanMapper.map(systemConfig, SystemConfigDTO.class));
            return new ResDto(ConstEum.SUCCESS, msgResult);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }

    /**
     * 更新系统参数
     *
     * @param msg
     * @return ResDto
     */
    @ApiParam("msg")
    @ApiOperation(value = "更新系统参数", notes = "SystemConfigId不可为null或者空字符")
    @RequestMapping(method = RequestMethod.PUT, name = "更新系统参数")
    public ResDto updateById(@RequestParam(required = true)
                             @ApiParam(name = "msg", value = "{\"id\":\"\", \"`key`\":\"\", \"value\":\"\", \"status\":\"\", \"mark\":\"\"}")
                                     String msg) {
        try {
            logger.info("入参 {}", msg);
            SystemConfig systemConfig = JsonMapper.defaultMapper().fromJson(msg, SystemConfig.class);
            if(systemConfig == null){
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            if (StringUtils.isBlank(systemConfig.getId())) {
                logger.error("ID不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            if (StringUtils.isBlank(systemConfig.getKey())) {
                logger.error("参数配置项不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            if (StringUtils.isBlank(systemConfig.getValue())) {
                logger.error("配置内容不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.handle.fail");
            }
            Integer status = systemConfig.getStatus();
            if (status==null || !(status==0 || status==1)) {
                logger.error("状态值不正确");
                return new ResDto(Const.PARAM_ERROR, "msg.handle.fail");
            }
            Wrapper<SystemConfig> systemConfigWrapper = new EntityWrapper<>();
            systemConfigWrapper.where("`key` = {0} and `id` != {1}", systemConfig.getKey(), systemConfig.getId());
            List<SystemConfig> systemConfigs = systemConfigService.selectList(systemConfigWrapper);
            if (systemConfigs != null && systemConfigs.size() > 0) {
                return new ResDto(Const.PARAM_ERROR, "msg.handle.fail.exist");
            }

            boolean isOk = systemConfigService.updateById(systemConfig);
            if (isOk) {
                return new ResDto(ConstEum.SUCCESS);
            } else {
                return new ResDto(Const.SERVER_ERROR, "msg.handle.fail");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }

    /**
     * 新增系统参数
     *
     * @param msg
     * @return ResDto
     */
    @ApiParam("msg")
    @ApiOperation(value = "新增系统参数", notes = "参数封装到SystemConfig")
    @RequestMapping(method = RequestMethod.POST, name = "新增系统参数")
    public ResDto insert(@RequestParam(required = true)
                         @ApiParam(name = "msg", value = "{\"`key`\":\"\", \"value\":\"\", \"status\":\"\", \"mark\":\"\"}")
                                 String msg) {
        try {
            logger.info("入参 {}", msg);
            SystemConfig systemConfig = JsonMapper.defaultMapper().fromJson(msg, SystemConfig.class);
            if(systemConfig == null){
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            if (StringUtils.isBlank(systemConfig.getKey())) {
                logger.error("参数配置项不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            if (StringUtils.isBlank(systemConfig.getValue())) {
                logger.error("配置内容不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.handle.fail");
            }
            Wrapper<SystemConfig> systemConfigWrapper = new EntityWrapper<>();
            systemConfigWrapper.where("`key` = {0}", systemConfig.getKey());
            List<SystemConfig> systemConfigs = systemConfigService.selectList(systemConfigWrapper);
            if (systemConfigs != null && systemConfigs.size() > 0) {
                return new ResDto(Const.PARAM_ERROR, "msg.handle.fail.exist");
            }

            boolean isOk = systemConfigService.insert(systemConfig);
            if (isOk) {
                return new ResDto(ConstEum.SUCCESS);
            } else {
                return new ResDto(Const.SERVER_ERROR, "msg.add.fail");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }

    /**
     * 删除系统参数
     *
     * @param id
     * @return ResDto
     */
    @ApiParam("id")
    @ApiOperation(value = "删除系统参数", notes = "id参数必传")
    @RequestMapping(value = "/${id}", method = RequestMethod.DELETE, name = "删除系统参数")
    public ResDto deleteById(@PathVariable String id) {
        try {
            logger.info("入参 {}", id);
            if (StringUtils.isBlank(id)) {
                logger.error("ID不能为空");
                return new ResDto(Const.PARAM_ERROR, "msg.param.error");
            }
            boolean isOk = systemConfigService.deleteById(id);
            if (isOk) {
                return new ResDto(ConstEum.SUCCESS);
            } else {
                return new ResDto(Const.SERVER_ERROR, "msg.delete.fail");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }
}
